<template>
  <view class="checkout-container">
    <!-- 商品列表 -->
    <view class="goods-section">
      <view class="goods-item" v-for="(item, index) in orderGoods" :key="index">
        <image class="goods-img" :src="item.image" mode="aspectFill"></image>
        <view class="goods-info">
          <text class="goods-name">{{item.name}}</text>
          <text class="goods-price">¥{{item.price.toFixed(2)}}</text>
          <text class="goods-num">x{{item.number}}</text>
        </view>
      </view>
    </view>
    
    <!-- 订单信息 -->
    <view class="order-section">
      <view class="order-item">
        <text>商品总价</text>
        <text class="price">¥{{totalPrice.toFixed(2)}}</text>
      </view>
      <view class="order-item">
        <text>运费</text>
        <text class="price">¥{{freight.toFixed(2)}}</text>
      </view>
      <view class="order-item total">
        <text>实付金额</text>
        <text class="price">¥{{actualPrice.toFixed(2)}}</text>
      </view>
    </view>
    
    <!-- 支付宝支付表单 -->
    <form id="alipayForm" ref="alipayForm" method="post" target="_blank" style="display: none;"></form>
    
    <!-- 支付按钮 -->
    <view class="footer">
      <view class="total-box">
        <text class="price">¥{{actualPrice.toFixed(2)}}</text>
      </view>
      <view class="submit" @click="submitOrder">提交订单</view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';

// 请求工具方法
const request = async (options) => {
  const token = uni.getStorageSync('token');
  if (!token && options.needToken !== false) {
    throw new Error('请先登录');
  }

  const baseUrl = import.meta.env.VITE_APP_BASE_API || '';
  
  return new Promise((resolve, reject) => {
    uni.request({
      ...options,
      url: baseUrl + options.url,
      header: {
        'Content-Type': 'application/json',
        'Authorization': token ? `Bearer ${token}` : '',
        ...options.header
      },
      success: (res) => {
        if (res.statusCode === 200) {
          if (res.data.code === 200 || res.data.code === 0) {
            resolve(res.data);
          } else {
            reject(new Error(res.data.message || '请求失败'));
          }
        } else if (res.statusCode === 401) {
          // 未登录或token过期
          uni.removeStorageSync('token');
          reject(new Error('请重新登录'));
        } else {
          reject(new Error(`请求失败: ${res.statusCode}`));
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        reject(new Error('网络请求失败，请检查网络连接'));
      }
    });
  });
};

// 订单商品
const orderGoods = ref([]);
// 运费
const freight = ref(0);

// 计算商品总价
const totalPrice = computed(() => {
  return orderGoods.value.reduce((total, item) => {
    return total + (item.price * item.number);
  }, 0);
});

// 计算实付金额
const actualPrice = computed(() => {
  return totalPrice.value + freight.value;
});

// 提交订单
const submitOrder = async () => {
  try {
    // 检查是否有商品
    if (!orderGoods.value || orderGoods.value.length === 0) {
      throw new Error('没有选中的商品');
    }

    // 创建订单
    const orderRes = await request({
      url: '/api/orders/create',
      method: 'POST',
      data: {
        remark: '',
        shippingId: null,
        selectedCartItems: orderGoods.value.map(item => item.id)
      }
    });

    const orderNo = orderRes.data;
    if (!orderNo) {
      throw new Error('未获取到订单号');
    }

    // 调用支付
    const payRes = await request({
      url: '/api/pay/create',
      method: 'POST',
      params: {  // 使用params而不是data，因为后端使用@RequestParam
        orderId: orderNo,
        amount: actualPrice.value.toFixed(2),
        subject: '智能零售货架订单'
      }
    });

    if (!payRes.data) {
      throw new Error('获取支付链接失败');
    }

    // 创建一个临时div来解析支付宝返回的表单
    const div = document.createElement('div');
    div.innerHTML = payRes.data;
    
    // 获取支付宝返回的表单数据
    const form = div.getElementsByTagName('form')[0];
    if (!form) {
      throw new Error('支付表单生成失败');
    }

    // 获取表单中的所有输入字段
    const inputs = form.getElementsByTagName('input');
    const formData = {};
    for (let input of inputs) {
      formData[input.name] = input.value;
    }

    // 获取支付宝网关地址
    const action = form.action;

    // 使用我们自己的表单提交
    const alipayForm = document.getElementById('alipayForm');
    alipayForm.action = action;

    // 清空原有的表单内容
    alipayForm.innerHTML = '';

    // 添加所有支付参数
    Object.keys(formData).forEach(key => {
      const input = document.createElement('input');
      input.type = 'hidden';
      input.name = key;
      input.value = formData[key];
      alipayForm.appendChild(input);
    });

    // 提交表单
    alipayForm.submit();

  } catch (e) {
    console.error('订单处理失败:', e);
    uni.showModal({
      title: '创建订单失败',
      content: e.message || '未知错误',
      showCancel: false
    });
  }
};

// 页面加载
onLoad((options) => {
  console.log('接收到的购物车数据:', options.cartItems);
  try {
    // 获取购物车选中的商品
    const cartItems = JSON.parse(decodeURIComponent(options.cartItems || '[]'));
    console.log('解析后的商品数据:', cartItems);
    
    // 确保每个商品项都有必要的字段
    orderGoods.value = cartItems.map(item => ({
      id: item.id || item.productId, // 兼容两种ID字段
      name: item.name || item.productName,
      image: item.image || item.mainImageUrl,
      price: parseFloat(item.price),
      number: item.number || item.quantity
    }));
    
    console.log('处理后的订单商品数据:', orderGoods.value);
    
    // 如果没有商品数据，提示并返回
    if (orderGoods.value.length === 0) {
      uni.showToast({
        title: '没有选中的商品',
        icon: 'none'
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    }
  } catch (e) {
    console.error('解析购物车数据失败:', e);
    uni.showToast({
      title: '加载订单数据失败',
      icon: 'none'
    });
  }
});
</script>

<style lang="scss">
.checkout-container {
  min-height: 100vh;
  background: #f8f8f8;
  padding-bottom: 120rpx;
  
  .goods-section {
    background: #fff;
    margin-bottom: 20rpx;
    
    .goods-item {
      display: flex;
      padding: 30rpx;
      border-bottom: 1rpx solid #f5f5f5;
      
      .goods-img {
        width: 160rpx;
        height: 160rpx;
        margin-right: 20rpx;
      }
      
      .goods-info {
        flex: 1;
        position: relative;
        
        .goods-name {
          font-size: 28rpx;
          color: #333;
          margin-bottom: 10rpx;
        }
        
        .goods-price {
          color: #ff6700;
          font-size: 32rpx;
        }
        
        .goods-num {
          position: absolute;
          right: 0;
          bottom: 0;
          color: #999;
        }
      }
    }
  }
  
  .order-section {
    background: #fff;
    padding: 30rpx;
    
    .order-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 20rpx;
      font-size: 28rpx;
      
      .price {
        color: #ff6700;
      }
      
      &.total {
        margin-top: 30rpx;
        padding-top: 30rpx;
        border-top: 1rpx solid #f5f5f5;
        font-size: 32rpx;
        font-weight: bold;
      }
    }
  }
  
  .footer {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 100rpx;
    background: #fff;
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
    
    .total-box {
      flex: 1;
      
      .price {
        color: #ff6700;
        font-size: 36rpx;
        font-weight: bold;
      }
    }
    
    .submit {
      width: 240rpx;
      height: 80rpx;
      background: #ff6700;
      color: #fff;
      text-align: center;
      line-height: 80rpx;
      border-radius: 40rpx;
    }
  }
}
</style> 